<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import RoleApi from '@/api/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ElMessage, ElTag } from 'element-plus'
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import UnallocatedUser from './UnallocatedUser.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter, useRoute } from 'vue-router'
const { t } = useI18n()
const { go } = useRouter()
const roleId = ref<any>(useRoute().query.roleId)
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await RoleApi.GetAuthUser({
      roleId: unref(roleId),
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows || [],
      total: res.total || 0
    }
  },
  fetchDelApi: async () => {
    console.log(unref(ids)[0])
    const data = { userId: unref(ids)[0], roleId: unref(roleId) }
    const res = await RoleApi.CancelAuthUser(data)
    return !!res
  }
})

const { dataList, loading, pageSize, total, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'userName',
    label: '用户名称',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '用户名称'
      }
    }
  },
  {
    field: 'nickName',
    label: '用户昵称',
    search: {
      hidden: true
    }
  },
  {
    field: 'status',
    label: '状态',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.row.status == '0' ? 'success' : 'danger'}>
                {data.row.status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'phonenumber',
    label: '手机号',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '手机号'
      }
    }
  },
  {
    field: 'email',
    label: '邮箱',
    search: {
      hidden: true
    }
  },

  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data) => {
          if (data.row.admin == false) {
            return (
              <>
                <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                  取消授权
                </span>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
const ids = ref<number[]>([])
const delLoading = ref(false)
const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.userId] : elTableExpose?.getSelectionRows().map((v: any) => v.userId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const currentRow = ref()
const actionType = ref('')

const dataScopeRef = ref<ComponentRef<any>>()
const saveLoading = ref(false)
const action = (row: any, type: string) => {
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}
const save = async () => {
  const dataScope = unref(dataScopeRef)
  const formDataScope = await dataScope?.submit()
  if (formDataScope) {
    saveLoading.value = true
    const res = await RoleApi.EditAuthUser({
      userIds: formDataScope,
      roleId: unref(roleId)
    })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
//比量取消授权
const BatchCancel = async () => {
  const elTableRef = await getElTableExpose()
  const selections = elTableRef?.getSelectionRows()
  if (selections.length == 0) {
    ElMessage.error('请先选择取消授权的用户！')
  } else {
    const userIds = selections.map((item) => {
      return item.userId
    })
    const res = await RoleApi.BatchCancelAuthUser({
      userIds: userIds,
      roleId: unref(roleId)
    })
    if (res) {
      ElMessage.success('取消授权成功！')
      getList()
    } else {
      ElMessage.error('取消授权失败！')
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton size="small" plain type="warning" @click="go(-1)" class="AddbtnStyle">
        <Icon icon="ep:back" :size="12" />退出
      </BaseButton>
      <BaseButton size="small" plain type="danger" @click="BatchCancel" class="AddbtnStyle">
        <Icon icon="ep:close" :size="12" />批量取消授权
      </BaseButton>
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="12" />添加角色
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      row-key="userId"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog style="width: 1200px" v-model="dialogVisible" title="选择用户">
    <UnallocatedUser ref="dataScopeRef" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
</style>
